import React, { useEffect, useMemo, useState } from 'react';
import { CommonModal } from '../../../CommonModal';
import { EditIndexModal } from '../../../EditIndexModal';
import { CommonTable } from '../CommonTable';
function flattenColumnConfigs(columnConfigs) {
    const data = [];
    function dfs(columnConfigs) {
        columnConfigs.forEach((config) => {
            data.push(config);
            if (config.childrenNode) {
                dfs(config.childrenNode);
            }
        });
    }
    dfs(columnConfigs);
    return data;
}
/**
 * 可编辑指标的table
*/
export const EditIndexTable = React.memo(function (params) {
    const { visible, defaultCheckedColumns, columnConfigs = [], columns = [], rowKey, modalTitle, checked, onChangeChecked, onVisibleChange, onCommit, ...args } = params;
    const [columnConfigsData, setColumnConfigsData] = useState(columnConfigs.filter(el => !el.hide));
    const [tmpChecked, setTmpChecked] = useState(new Map());
    const [commit, setCommit] = useState({
        checked,
        columnConfigsData
    });
    useEffect(() => {
        setTmpChecked(checked);
        setCommit((pre) => ({ ...pre, checked }));
    }, [checked]);
    const resolvedColumns = useMemo(() => {
        if (!defaultCheckedColumns && !columnConfigs) {
            return columns;
        }
        const { checked } = commit;
        const res = [];
        const { columnConfigsData } = commit;
        const columnsOrderConfig = flattenColumnConfigs(columnConfigsData)
            .reduce((prev, next) => {
            prev.add(next.field);
            return prev;
        }, new Set());
        columnsOrderConfig.forEach((config) => {
            if (checked.get(config)) {
                const item = columns.find((el) => el?.dataIndex === config);
                res.push(item);
            }
        });
        return res.filter(Boolean);
    }, [columns, commit]);
    return (<>
      <CommonModal width={548} title={{
            title: "筛选字段设置",
            ...modalTitle,
        }} open={visible} onCancel={(e) => {
            onChangeChecked(commit.checked);
            setColumnConfigsData(commit.columnConfigsData);
            onVisibleChange?.(false);
        }} onOk={(e) => {
            const commitData = {
                checked: tmpChecked,
                columnConfigsData
            };
            setCommit(commitData);
            onCommit?.(commitData);
            onChangeChecked?.(commit.checked);
            onVisibleChange?.(false);
        }}>
        <EditIndexModal value={columnConfigsData} onValueChange={setColumnConfigsData} showAllCheckBox checkedColumns={tmpChecked} onCheckedColumnsChange={setTmpChecked}/>
      </CommonModal>
      <CommonTable {...args} columns={resolvedColumns}/>
    </>);
});
export default EditIndexTable;
